//
//  BCLALoginPasswordController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/7.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCLALoginPasswordController.h"

//request
#import "BCUserFingerPrintRequest.h"

static CGFloat BCLALoginPasswordControllerTopPadding = 75.0;
static CGFloat BCLALoginPasswordControllerTFHeight = 50.0;
static CGFloat BCLALoginPasswordControllerBottomMinPadding = 75.0;

@interface BCLALoginPasswordController () <QMUITextFieldDelegate>


/**
 *BCLALoginPasswordControllerBlcok
 */
@property (nonatomic, copy) BCLALoginPasswordControllerBlcok completeBlcok;

@property (nonatomic, strong) QMUITextField *passwordTF;

/**
 *topView
 */
@property (nonatomic, strong) UIView *topView;
/**
 *backButton
 */
@property (nonatomic, strong) QMUIButton *backButton;

/**
 *titleLabel
 */
@property (nonatomic, strong) QMUILabel *titleLabel;

/**
 *forgotPassButton
 */
@property (nonatomic, strong) QMUIButton *forgotButton;


#pragma mark - flag

/**
 *loadingFlay
 */
@property (nonatomic, assign) BOOL loadingFlag;

@end

@implementation BCLALoginPasswordController

+ (void)showLoginPasswordComplete:(BCLALoginPasswordControllerBlcok)complete {
    BControllerWindow *window = [[BControllerWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    window.windowLevel = UIWindowLevelAlert;
    //vc
    BCLALoginPasswordController *vc = [BCLALoginPasswordController new];
    vc.showWindow = window;
    vc.completeBlcok = complete;
    BCWindowNavigationController *nav = [[BCWindowNavigationController alloc] initWithRootViewController:vc];
    nav.navigationBar.hidden = true;
    nav.navigationBar.barStyle = UIBarStyleDefault;
    window.rootViewController = nav;
    [window makeKeyAndVisible];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
}
- (CGFloat)contentHeight {
    return BCLALoginPasswordControllerTopPadding+50.0+BCLALoginPasswordControllerBottomMinPadding;
}

- (void)setupSubviews {
    [self.view addSubview:self.backgroundView];
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    //
    CGFloat contentHeight = [self contentHeight];
    [self.view addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view);
        make.width.mas_equalTo(self.view);
        make.height.mas_equalTo(contentHeight);
        make.bottom.mas_equalTo(self.view);
    }];
    //
    [self setupContents];
}

- (void)setupContents {
    self.topView = [UIView new];
    [self.contentView addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self.contentView);
        make.height.mas_equalTo(60.0);
    }];
    //
    self.backButton = [QMUIButton new];
    [self.backButton setImage:[LOAD_IMAGE(@"navi_arrow_left") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    self.backButton.tintColor = [UIColor qmui_colorWithHexString:@"#222222"];
    [self.topView addSubview:self.backButton];
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.topView).offset(5.0);
        make.centerY.mas_equalTo(self.topView);
    }];
    
    [self.backButton addTarget:self action:@selector(backButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    //
    self.titleLabel = [QMUILabel new];
    self.titleLabel.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.titleLabel.numberOfLines = 2;
    self.titleLabel.adjustsFontSizeToFitWidth = true;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    [self.topView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.topView);
        make.centerY.mas_equalTo(self.topView);
        make.height.mas_equalTo(self.topView);
        make.width.mas_lessThanOrEqualTo(self.topView).offset(-200.0);
    }];
    //
    self.titleLabel.text = BCLocalizedKey(@"Please input login password");
    
    //
    self.passwordTF = [QMUITextField new];
    self.passwordTF.textColor = [UIColor qmui_colorWithHexString:@"#000000"];
    self.passwordTF.tintColor = self.passwordTF.textColor;
    self.passwordTF.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.passwordTF.secureTextEntry = true;
    self.passwordTF.textAlignment = NSTextAlignmentCenter;
    self.passwordTF.textInsets = UIEdgeInsetsMake(4, 5, 4, 5);
    [self.contentView addSubview:self.passwordTF];
    [self.passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView).offset(BCLALoginPasswordControllerTopPadding);
        make.centerX.mas_equalTo(self.contentView);
        make.width.mas_equalTo(self.contentView).offset(-40.0);
        make.height.mas_equalTo(BCLALoginPasswordControllerTFHeight);
    }];
    self.passwordTF.layer.cornerRadius = 2;
    self.passwordTF.layer.borderColor = [UIColor qmui_colorWithHexString:@"#FFC2C2C2"].CGColor;
    self.passwordTF.layer.borderWidth = 2;
    //
    self.passwordTF.inputAccessoryView = [UIView new];
    self.passwordTF.enablesReturnKeyAutomatically = true;
    self.passwordTF.returnKeyType = UIReturnKeyDone;
    //
    self.passwordTF.delegate = self;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = false;
    //
    [self.passwordTF becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = true;
}

#pragma mark - QMUITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (self.loadingFlag) {
        return false;
    }
    return true;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (!self.loadingFlag) {
        [self requestOperationFingerPrint];
    }
    return true;
}


#pragma mark - loading
- (void)startLoading {
    self.loadingFlag = true;
    self.topView.alpha = 0.5;
    self.topView.userInteractionEnabled = false;
    [self.passwordTF bc_showActivityIndicatorBackgroundColor:self.contentView.backgroundColor insets:self.passwordTF.textInsets];
}
- (void)stopLoading {
    self.loadingFlag = false;
    self.topView.alpha = 1;
    self.topView.userInteractionEnabled = true;
    [self.passwordTF bc_hiddenActivityIndicator];
}



#pragma mark - backButtonDidClickedAction
- (void)backButtonDidClickedAction {
    [self dismissWindow];
}

#pragma mark - request
- (void)requestOperationFingerPrint {
    [self startLoading];
    BCUserFingerPrintRequest *request = [BCUserFingerPrintRequest new];
    //
    NSString *password = self.passwordTF.text;
    request.password = password;
    //
    NSString *uid = [BCUserManager sharedUser].userLogin.user_id;
    request.fingerprint = [[BCUserLoginManager sharedLogin] userInitLocalAuthenticationCode:uid password:password];
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself stopLoading];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCUserFingerPrintRequest *resp = result;
        [wself handleSuccessResponseData:resp];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:[UIApplication sharedApplication].keyWindow hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        }
    }];
    [request requestServer];
}
- (void)handleSuccessResponseData:(id)respData {
    if (self.completeBlcok) {
        self.completeBlcok(true);
    }
    [self backButtonDidClickedAction];
}


- (void)dealloc {
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = true;
}

@end
